package com.bodacn.storagescan;

import android.app.Activity;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class CallAgvActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG = this.getClass().getName();
    private final static int MSG_AllowScan=9000;
    private final static int MSG_ScanBarcodeOver=9001;
    private final static int MSG_FocusBarcode =9002;
    public static final int MSG_GETPATH=9003;
    public static final int MSG_PUTNEXT=9004;
    public static final int MSG_AGVREC=9005;

    TextView txt_titleInv, tv_barcodeCaption,tv_ResultInfo,tv_CallTitle;
    FrameLayout liner_title;
    Button btn_Query, btn_moveFull,btn_moveInFull,btn_moveSpace,btn_moveInSpace;
    ImageButton btn_return;
    EditText edit_Barcode,edt_TrayCode,edt_PlaceNo;
    String curLoginUserNo,curLoginUser,curLoginTime;//操作员所属部门等信息;
    String FormType="",Caption="",PrBarcode="",CallTitle="";
    int curAgvReqIndex=0;
    boolean ScanSign=false;
    //拦截扫描枪输入部分
    String BarcodeStr="",TrayCode="",CallFunc="";
    ScannerManager scannerManager;
    private MainApplication mApp;
    JSONArray detailJSON,callJSON,pathJSON;
    String TaskID= UUID.randomUUID().toString();
    //全局变量
    Toast curToast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_callagv);
        InitView();
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curLoginTime=paramBundle.getString("LoginTime");
        FormType=paramBundle.getString("FormType");
        Caption=paramBundle.getString("Caption");
        CallTitle=paramBundle.getString("CallTitle");
        TrayCode=paramBundle.getString("TrayCode");
        CallFunc=paramBundle.getString("CallFunc","MoveFull;");
        if (CallFunc.indexOf("MoveFull")==-1&&CallFunc.indexOf("AllFunc")==-1) btn_moveFull.setVisibility(View.GONE);
        if (CallFunc.indexOf("MoveInFull")==-1&&CallFunc.indexOf("AllFunc")==-1) btn_moveInFull.setVisibility(View.GONE);
        if (CallFunc.indexOf("MoveSpace")==-1&&CallFunc.indexOf("AllFunc")==-1) btn_moveSpace.setVisibility(View.GONE);
        if (CallFunc.indexOf("MoveInSpace")==-1&&CallFunc.indexOf("AllFunc")==-1) btn_moveInSpace.setVisibility(View.GONE);
        tv_CallTitle.setText(CallTitle);
        edt_TrayCode.setText(TrayCode);
        //界面变量
        ((TextView)findViewById(R.id.tv_userName)).setText("用户:"+curLoginUser);
        //置标题颜色
        txt_titleInv.setText(Caption);
        txt_titleInv.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新界面;
                Message msg = new Message();
                msg.what = MSG_FocusBarcode;
                handler.removeMessages(msg.what);
                handler.sendMessage(msg);
            }
        },200);
        mApp=  (MainApplication) getApplication();
        //初始提醒;
        curToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }

    //判断是否为数字，不然不转
    public static boolean isNumer(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    private void InitView(){
        btn_Query=findViewById(R.id.btn_Scan);
        btn_Query.setOnClickListener(this);
        tv_ResultInfo=findViewById(R.id.tv_ResultInfo);
        tv_CallTitle=findViewById(R.id.tv_CallTitle);
        edt_PlaceNo=findViewById(R.id.edt_PlaceNo);
        edt_TrayCode=findViewById(R.id.edt_TrayCode);
        edit_Barcode=findViewById(R.id.edit_Barcode);
        edit_Barcode.setInputType(InputType.TYPE_NULL);
        edit_Barcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edit_Barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_Barcode, InputMethodManager.SHOW_FORCED);
            }
        });
        edit_Barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    //Log.e("Debug","-----------------------------Debug-----------------------------");
                    //System.out.println(event);
                    if ((event.getAction()== KeyEvent.ACTION_UP)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        //System.out.println(edit_Barcode.getText().toString());
                        String code=edit_Barcode.getText().toString();
                        edit_Barcode.setHint(code);
                        ScanBarcode(code);
                        edit_Barcode.setText("");
                        return true;
                    }
                }
                return false;
            }
        });
        edit_Barcode.requestFocus();
        edit_Barcode.requestFocusFromTouch();
        liner_title=findViewById(R.id.liner_title);
        tv_barcodeCaption =findViewById(R.id.tv_barcodeCaption);
        txt_titleInv=findViewById(R.id.txt_titleInv);
        btn_return =findViewById(R.id.btn_return);
        btn_return.setOnClickListener(this);
        btn_moveFull =findViewById(R.id.btn_moveFull);
        btn_moveFull.setOnClickListener(this);
        btn_moveInFull =findViewById(R.id.btn_moveInFull);
        btn_moveInFull.setOnClickListener(this);
        btn_moveSpace =findViewById(R.id.btn_moveSpace);
        btn_moveSpace.setOnClickListener(this);
        btn_moveInSpace =findViewById(R.id.btn_moveInSpace);
        btn_moveInSpace.setOnClickListener(this);

    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View view) {
        hideIM(view);
        switch (view.getId()){
            case R.id.btn_moveFull:
                if (edt_PlaceNo.getText().toString().length()>0&&edt_TrayCode.getText().toString().length()>0) {
                    GetCallPath(edt_TrayCode.getText().toString(), edt_PlaceNo.getText().toString(),"MoveFull");
                } else{
                    Toast.makeText(getApplicationContext(),"请扫描托盘号及库位号!", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btn_moveInFull:
                if (edt_PlaceNo.getText().toString().length()>0) {
                    GetCallPath(edt_TrayCode.getText().toString(), edt_PlaceNo.getText().toString(),"MoveInFull");
                } else{
                    Toast.makeText(getApplicationContext(),"请扫描库位号!", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btn_moveSpace:
                if (edt_PlaceNo.getText().toString().length()>0&&edt_TrayCode.getText().toString().length()>0) {
                    GetCallPath(edt_TrayCode.getText().toString(), edt_PlaceNo.getText().toString(),"MoveSpace");
                } else{
                    Toast.makeText(getApplicationContext(),"请扫描托盘号及库位号!", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btn_moveInSpace:
                if (edt_PlaceNo.getText().toString().length()>0) {
                    GetCallPath(edt_TrayCode.getText().toString(), edt_PlaceNo.getText().toString(),"MoveInSpace");
                } else{
                    Toast.makeText(getApplicationContext(),"请扫描库位号!", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btn_return:
                finish();//关闭当前Activity，返回上一级;
                break;
            case R.id.btn_Scan:
                if ((edit_Barcode.getText()!=null)&&(edit_Barcode.getText().length()>0)) {
                    String code=edit_Barcode.getText().toString();
                    edit_Barcode.setHint(code);
                    ScanBarcode(code);
                    edit_Barcode.setText("");
                } else Toast.makeText(getApplicationContext(),"请先输入条码!", Toast.LENGTH_LONG).show();
                break;
            case R.id.btn_refreshDetail:

                hideIM(liner_title);
                break;
            default:
                break;
        }
    }

    //呼叫AGV
    private void GetCallPath(String toTrayCode, String toPlaceNo,String paramCallType) {
        //调用过程获取路径
        System.out.println("getDepartment------------------------------------->");
        try {
            pathJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm = "Exec AGV_GetPath @OPERTYPE='GETPATH',@TrayCode='"+toTrayCode
                +"',@PlaceNo='"+toPlaceNo+"',@CallType='"+paramCallType
                +"',@userNo='"+curLoginUserNo+"',@userName='"+curLoginUser+"'";
        ReadSQLData(SqlComm);
    }
    //呼叫AGV
    private void AGVRecOK(String paramReqCode, String paramTaskCode) {
        //调用过程获取路径
        System.out.println("getDepartment------------------------------------->");
        //执行SQL过程
        String SqlComm = "Exec AGV_CallBack @OPERTYPE='AGVREC',@ReqCode='"+paramReqCode+"',@TaskCode='"+paramTaskCode+"',@userNo='"+curLoginUserNo+"',@userName='"+curLoginUser+ "'";
        ReadSQLData(SqlComm);
    }

    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            hideIM(edit_Barcode);
            ScanSign=false;
            switch (msgId) {
                case MSG_GETPATH:
                    if (pathJSON!=null&&pathJSON.length()>0){
                        if (pathJSON.optJSONObject(0).has("ReqCode")&&pathJSON.optJSONObject(0).has("StartPlace")&&pathJSON.optJSONObject(0).has("EndPlace")){
                            curAgvReqIndex=0;
                            try {
                                PutAGVTask(pathJSON.optJSONObject(curAgvReqIndex).getString("ReqCode"),
                                        pathJSON.optJSONObject(curAgvReqIndex).getString("StartPlace"),
                                        pathJSON.optJSONObject(curAgvReqIndex).getString("EndPlace"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
                case MSG_AGVREC:
                    //可以通过回调成功来继续后面任务;
                case MSG_PUTNEXT:
                    System.out.println("MSG_AGVREC&MSG_PUTNEXT:"+curAgvReqIndex+":"+pathJSON.length());
                    if (curAgvReqIndex<(pathJSON.length()-1)){
                        curAgvReqIndex++;
                        try {
                            PutAGVTask(pathJSON.optJSONObject(curAgvReqIndex).getString("ReqCode"),
                                    pathJSON.optJSONObject(curAgvReqIndex).getString("StartPlace"),
                                    pathJSON.optJSONObject(curAgvReqIndex).getString("EndPlace"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case MSG_FocusBarcode:
                    edit_Barcode.setEnabled(true);
                    edit_Barcode.selectAll();
                    edit_Barcode.requestFocus();
                    edit_Barcode.requestFocusFromTouch();
                    break;
                case MSG_ScanBarcodeOver:
                    fillScreen();
                    break;
                case MSG_AllowScan:
                    ScanSign=false;
                    break;
                default:
                    break;
            }
        }
    };




    private void PutAGVTask(String paramReqCode,String paramStartPlace,String paramEndPlace){
        try {
            JSONArray positionCodePath=new JSONArray("[]");
            JSONObject codePath = new JSONObject();
            codePath.put("positionCode",paramStartPlace);
            codePath.put("type","00");
            positionCodePath.put(codePath);
            codePath = new JSONObject();
            codePath.put("positionCode",paramEndPlace);
            codePath.put("type","00");
            positionCodePath.put(codePath);
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("reqCode", paramReqCode);
            jsonParam.put("reqTime", "");
            jsonParam.put("tokenCode", "");
            jsonParam.put("interfaceName", "genAgvSchedulingTask");
            jsonParam.put("taskTyp", "PTP");
            jsonParam.put("wbCode", "");
            jsonParam.put("positionCodePath", positionCodePath);
            jsonParam.put("podCode", "");
            jsonParam.put("podDir", "");
            jsonParam.put("priority", "");
            jsonParam.put("agvCode", "");
            jsonParam.put("taskCode", "");
            jsonParam.put("data", "");
            System.out.println(jsonParam);
            //提交参数;
            sendJsonPost(mApp.AgvUrl,"genAgvSchedulingTask",jsonParam.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public void sendJsonPost(String serviceUrl, String methodName, String Json) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("methodName",methodName);
        params.put("Json",Json);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected String doInBackground(Map<String, Object>... params) {
                String serviceUrl= (String) params[0].get("serviceUrl");
                System.out.println(serviceUrl);
                String methodName= (String) params[0].get("methodName");
                String Json= (String) params[0].get("Json");
                // HttpClient 6.0被抛弃了
                String result = null;
                BufferedReader reader = null;
                try {
                    System.out.println("sendCancelJsonPost:"+methodName);
                    String urlPath = serviceUrl + methodName;
                    Log.e("sendCancelJsonPost",urlPath);
                    URL url = new URL(urlPath);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("Charset", "UTF-8");
                    conn.setRequestProperty("User-Agent","");
                    // 设置文件类型:
                    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                    // 设置接收类型否则返回415错误
                    //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
                    conn.setRequestProperty("accept", "application/json");
                    // 往服务器里面发送数据
                    if (Json != null && !TextUtils.isEmpty(Json)) {
                        byte[] writebytes = Json.getBytes();
                        // 设置文件长度
                        conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                        OutputStream outwritestream = conn.getOutputStream();
                        outwritestream.write(Json.getBytes());
                        outwritestream.flush();
                        outwritestream.close();
                        Log.d("hlhupload", "doJsonPost: conn-----" + conn.getResponseCode());
                    }
                    if (conn.getResponseCode() == 200) {
                        reader = new BufferedReader(
                                new InputStreamReader(conn.getInputStream()));
                        result = reader.readLine();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                System.out.println(result);
                return result;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s==null) {
                    tv_ResultInfo.setText("调用失败!");
                    return;
                }
                //这部分主要用于UI更新;
                System.out.println("onPostExecute:"+s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.has("data")&&jsonObject.has("message")&&jsonObject.has("reqCode")){
                        if (jsonObject.getString("message").equals("成功")) {
                            //调用任务成功回调;
                            AGVRecOK(jsonObject.getString("reqCode"), jsonObject.getString("data"));
                            //最后一条命令则给上调用成功;
                            if (pathJSON!=null) {
                                if (curAgvReqIndex == pathJSON.length() - 1)
                                    tv_ResultInfo.setText("AGV调度指令发送成功-"+jsonObject.getString("message"));
                                else tv_ResultInfo.setText("AGV调度准备发送第" + curAgvReqIndex + '条');
                            }
                            curToast.setText(jsonObject.getString("message"));
                            curToast.show();
                        } else {
                            tv_ResultInfo.setText("AGV调用失败！");
                            if (jsonObject.has("message")) {
                                curToast.setText(jsonObject.getString("message"));
                                curToast.show();
                            }

                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }.execute(params);

    }



    private void fillScreen() {
        if (detailJSON!=null&&detailJSON.length()>0){
            try {
                if (detailJSON.optJSONObject(0).has("TrayCode")) edt_TrayCode.setText(detailJSON.optJSONObject(0).getString("TrayCode"));
                if (detailJSON.optJSONObject(0).has("PlaceNo")) edt_PlaceNo.setText(detailJSON.optJSONObject(0).getString("PlaceNo"));
                if (detailJSON.optJSONObject(0).has("ResultInfo")) tv_ResultInfo.setText(detailJSON.optJSONObject(0).getString("ResultInfo"));
                if (detailJSON.optJSONObject(0).has("ErrInfo")) tv_ResultInfo.setText(detailJSON.optJSONObject(0).getString("ErrInfo"));
                if (detailJSON.optJSONObject(0).has("FontColor")) tv_ResultInfo.setTextColor(GetColorValue(detailJSON.optJSONObject(0).getString("FontColor")));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor= Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor= Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }


    //登陆校验;
    private void ScanBarcode(String paramBarcode){
        hideIM(edit_Barcode);
        try {
            detailJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String SqlComm = "Exec AGV_CallBarcode @Barcode='" + paramBarcode + "',@FormType='" + FormType + "',@TrayCode='" + edt_TrayCode.getText().toString()
                + "',@PlaceNo='" + edt_PlaceNo.getText().toString()+ "',@OperType='ScanBarcode',@UserNo='" + curLoginUserNo + "',@UserName='" + curLoginUser +"'";
        PrBarcode = paramBarcode;
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        ScanSign=true;
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                     String OperType="";
                    if (jsonArray.optJSONObject(0).has("OperType")) OperType=jsonArray.optJSONObject(0).getString("OperType");
                    if (jsonArray.optJSONObject(0).has("OPERTYPE")) OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (OperType.equals("ScanBarcode")==true||OperType.equals("Submit")==true){
                            detailJSON=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ScanBarcodeOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OperType.toUpperCase().equals("GETPATH"))
                        {
                            pathJSON=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_GETPATH;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OperType.toUpperCase().equals("AGVREC"))
                        {
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_AGVREC;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                    } else{
                        Message msg = new Message();
                        msg.what = MSG_AllowScan;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //刷新界面;
                    ScanSign=false;
                    Message msg = new Message();
                    msg.what = MSG_AllowScan;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();

    }




}
